//
//  STSpaceSubLiteratureView.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/11/9.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "STSpaceSubLiteratureView.h"

#import "CommonStwxItemCell.h"
#import "StwxDetailViewController.h"
#import "DocumentDetailViewController.h"

@interface STSpaceSubLiteratureView() <UITableViewDelegate, UITableViewDataSource>

/// 模型视图
@property (nonatomic, readonly, strong) STSpaceSubLiteratureViewModel* viewModel;

//IBOutlet
@property (weak, nonatomic) IBOutlet UITableView* tableView;

@end

@implementation STSpaceSubLiteratureView

- (void)bindViewModel:(id)viewModel
{
    STSpaceSubLiteratureViewModel* vm = viewModel;
    
    if (!self.viewModel)
    {
        _viewModel = vm;
        
        [self _setup];
    }
    else
    {
    }
}

- (void)_setup
{
    @weakify(self)
    
    [self _setupTableView];
}

- (void)_setupTableView
{
    @weakify(self);
    
    StwxTableViewModel* curTableVM = self.viewModel.stwxTVM;
    
    [[[[RACObserve(self.viewModel.stwxTVM, dataSource) distinctUntilChanged] filter:^BOOL(id value) {
        
        return value != nil;
    }] deliverOnMainThread]
     subscribeNext:^(id x) {
         @strongify(self)
         // 刷新数据
         
         NSArray* curArr = x;
         UITableView* curTableView = self.tableView;
         UIImageView* emptyTipView = [curTableView viewWithTag:199];
         emptyTipView.hidden = curArr.count > 0;
         
         [self.tableView reloadData];
     }];
    
    curTableVM.didSelectCommand = curTableVM.selectCmd;
    
    [[curTableVM.selectCmd.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x) {
        @strongify(self)
        
        CommonStwxItemViewModel* itemVM = x;
        //
        //            [self _push2Web:itemVM.articleData];
        
        if (itemVM.type == 2)
        {
            [self _push2DocumentDetailVCByArticleID:itemVM.articleID];
        }
        else
        {
            [self _push2StwxDetailVCByArticleID:itemVM.articleID];
        }
    }];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    /// 添加加载和刷新控件
    if (curTableVM.shouldPullDownToRefresh) {
        /// 下拉刷新
        [self.tableView mh_addHeaderRefresh:^(MJRefreshNormalHeader *header) {
            /// 加载下拉刷新的数据
            @strongify(self);
            [self tableViewDidTriggerHeaderRefresh:curTableVM];
        }];
        [self.tableView.mj_header beginRefreshing];
    }
    
    if (curTableVM.shouldPullUpToLoadMore) {
        /// 上拉加载
        @weakify(self);
        [self.tableView mh_addFooterRefresh:^(MJRefreshAutoNormalFooter *footer) {
            /// 加载上拉刷新的数据
            @strongify(self);
            [self tableViewDidTriggerFooterRefresh:curTableVM];
        }];
        
        /// 判断一下数据
        [self tableViewDidFinishTriggerHeader:NO reload:NO tableVM:curTableVM];
    }
    
#ifdef __IPHONE_11_0
    MHAdjustsScrollViewInsets_Never(self.tableView);
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
#endif
    
    [self.tableView mh_registerNibCell:[CommonStwxItemCell class]];
    
    UIImage* emptyTipImg = MHImageNamed(@"baocuo");
    UIImageView* emptyTipView = [[UIImageView alloc] initWithImage:emptyTipImg];
    emptyTipView.hidden = YES;
    CGPoint centerPoint = (CGPoint) {self.frame.size.width/2.0f, self.frame.size.height/2.0f + 22.0f};
    CGSize viewSize = (CGSize) {100, emptyTipImg.size.height*100/emptyTipImg.size.width};
    emptyTipView.frame = (CGRect) {centerPoint.x - viewSize.width/2.0f, centerPoint.y - viewSize.height/2.0f, viewSize};
    emptyTipView.tag = 199;
    UILabel* tipLabel = [[UILabel alloc] initWithFrame:(CGRect) {16, viewSize.height + 24, viewSize.width, 24}];
    tipLabel.text = @"暂无记录";
    tipLabel.textColor = UIColorHex(#bbbbbb);
    [emptyTipView addSubview:tipLabel];
    [self.tableView addSubview:emptyTipView];
}

#pragma mark -- sub class can override it
/// 下拉事件
- (void)tableViewDidTriggerHeaderRefresh:(StwxTableViewModel*)tableVM
{
    @weakify(self)
    NSDictionary* info = @{@"LoadIndex":@(0)};
    
    [[[tableVM.requestDataCmd
       execute:info]
      deliverOnMainThread]
     subscribeNext:^(id x) {
         @strongify(self)
         tableVM.page = 1;
     } error:^(NSError *error) {
         @strongify(self)
         [self tableViewDidFinishTriggerHeader:YES reload:NO tableVM:tableVM];
     } completed:^{
         @strongify(self)
         /// 已经在bindViewModel中添加了对viewModel.dataSource的变化的监听来刷新数据
         [self tableViewDidFinishTriggerHeader:YES reload:NO tableVM:tableVM];
     }];
}

/// 上拉事件
- (void)tableViewDidTriggerFooterRefresh:(StwxTableViewModel*)tableVM
{
    @weakify(self);
    NSDictionary* info = @{@"LoadIndex":@(tableVM.page)};
    
    [[[tableVM.requestDataCmd
       execute:info]
      deliverOnMainThread]
     subscribeNext:^(id x) {
         @strongify(self)
         tableVM.page += 1;
     } error:^(NSError *error) {
         @strongify(self);
         [self tableViewDidFinishTriggerHeader:NO reload:NO tableVM:tableVM];
     } completed:^{
         @strongify(self)
         [self tableViewDidFinishTriggerHeader:NO reload:NO tableVM:tableVM];
     }];
}

/// 刷新完成事件
- (void)tableViewDidFinishTriggerHeader:(BOOL)isHeader reload:(BOOL)reload tableVM:(StwxTableViewModel*)tableVM
{
    UITableView* findTableView = self.tableView;
    
    if (findTableView != NULL)
    {
        __weak STSpaceSubLiteratureView *weakSelf = self;
        dispatch_async(dispatch_get_main_queue(), ^{
            if (reload) {
                [findTableView reloadData];
            }
            if (isHeader) {
                [findTableView.mj_header endRefreshing];
            }
            else{
                [findTableView.mj_footer endRefreshing];
            }
            /// 最后一页隐藏加载控件
            findTableView.mj_footer.hidden = (tableVM.page>=tableVM.lastPage);
        });
    }
}

- (UIEdgeInsets)contentInset{
    return UIEdgeInsetsMake(64, 0, 0, 0);
}

/// config  cell
- (UITableViewCell *)tableView:(UITableView *)tableView dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath
{
    return [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([CommonStwxItemCell class])];
}

/// config  data
- (void)configureCell:(CommonStwxItemCell *)cell atIndexPath:(NSIndexPath *)indexPath withObject:(CommonStwxItemViewModel *)object{
    /// config data (PS：由于MVVM主要是View与数据之间的绑定，但是跟 setViewModel: 差不多啦)
    [cell bindViewModel:object];
}

#pragma mark -- UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.viewModel.stwxTVM.shouldMultiSections) return self.viewModel.stwxTVM.dataSource ? self.viewModel.stwxTVM.dataSource.count : 1;
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.viewModel.stwxTVM.shouldMultiSections) return [self.viewModel.stwxTVM.dataSource[section] count];
    
    return self.viewModel.stwxTVM.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Class cellClass = [CommonStwxItemCell class];
    
    UITableViewCell *cell = [self tableView:tableView dequeueReusableCellWithIdentifier:NSStringFromClass(cellClass) forIndexPath:indexPath];
    
    // fetch object
    id object = nil;
    if (self.viewModel.stwxTVM.shouldMultiSections) object = self.viewModel.stwxTVM.dataSource[indexPath.section][indexPath.row];
    if (!self.viewModel.stwxTVM.shouldMultiSections) object = self.viewModel.stwxTVM.dataSource[indexPath.row];
    
    /// bind model
    [self configureCell:(CommonStwxItemCell*)cell atIndexPath:indexPath withObject:(id)object];
    
    return cell;
}

#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return .0001f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    /// FIXED : when data is empty ，the backgroundColor is exist
    return .0001f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    /// 由于使用系统的autoLayout来计算cell的高度，每次滚动时都要重新计算cell的布局以此来获得cell的高度 这样一来性能不好
    /// 所以笔者采用实现计算好的cell的高度
    
    return [self.viewModel.stwxTVM.dataSource[indexPath.row] cellHeight];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    // execute commond
    
    [self.viewModel.stwxTVM.didSelectCommand execute:self.viewModel.stwxTVM.dataSource[indexPath.row]];
}

#pragma mark -- 跳转
- (void)_push2StwxDetailVCByArticleID:(NSString*)articleID
{
    StwxDetailViewModel* vm = [[StwxDetailViewModel alloc] initWithParams:@{}];
    vm.articleID = articleID;
    StwxDetailViewController* vc = [[StwxDetailViewController alloc] initWithViewModel:vm];
    UIViewController* showVC = [UIViewController getCurrentVC];
    
    UINavigationController* navc = showVC.navigationController;
    [navc pushViewController:vc animated:YES];
}
- (void)_push2DocumentDetailVCByArticleID:(NSString*)articleID
{
    DocumentDetailViewModel* vm = [[DocumentDetailViewModel alloc] initWithParams:@{}];
    vm.articleID = articleID;
    DocumentDetailViewController* vc = [[DocumentDetailViewController alloc] initWithViewModel:vm];
    UIViewController* showVC = [UIViewController getCurrentVC];
    
    UINavigationController* navc = showVC.navigationController;
    [navc pushViewController:vc animated:YES];
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
